import { defineStore } from 'pinia'
import { login, logout, getInfo } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  }),

  actions: {
    // 用户登录
    login(userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password }).then(response => {
          // 根据后端返回的数据结构调整
          const data = response.data || response
          
          // 如果后端返回的是用户信息，我们生成一个token或使用返回的token
          const token = data.token || data.id || 'temp_token_' + Date.now()
          
          this.token = token
          setToken(token)
          
          // 如果返回了用户信息，直接设置
          if (data.userName || data.userAccount) {
            this.name = data.userName || data.userAccount
            this.avatar = data.userAvatar || ''
            this.roles = data.userRole ? [data.userRole] : ['user']
            this.permissions = ['*:*:*'] // 默认权限
          }
          
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data || response

          if (!data) {
            reject('验证失败，请重新登录。')
          }

          // 适配后端返回的用户信息格式
          const name = data.nickname || 'admin'
          const avatar = data.userAvatar || ''
          const roles = data.userRole ? [data.userRole] : ['admin']
          const permissions = ['*:*:*'] // 默认给予所有权限

          this.roles = roles
          this.name = name
          this.avatar = avatar
          this.permissions = permissions

          resolve({
            name,
            avatar,
            roles,
            permissions,
            ...data
          })
        }).catch(error => {
          // 如果获取用户信息失败，使用默认信息
          console.warn('获取用户信息失败，使用默认信息:', error)
          const defaultData = {
            name: 'admin',
            avatar: '',
            roles: ['admin'],
            permissions: ['*:*:*']
          }
          
          this.roles = defaultData.roles
          this.name = defaultData.name
          this.avatar = defaultData.avatar
          this.permissions = defaultData.permissions
          
          resolve(defaultData)
        })
      })
    },

    // 用户登出
    logout() {
      return new Promise((resolve, reject) => {
        logout(this.token).then(() => {
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    fedLogOut() {
      return new Promise(resolve => {
        this.token = ''
        this.roles = []
        this.permissions = []
        removeToken()
        resolve()
      })
    }
  }
})